package com.sin.j2me.http;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import com.sin.j2me.common.ExceptionHandle;

public class HttpRequest{
	private HttpConnection con = null;
	private static void setConnection(HttpConnection con) throws IOException{
		con.setRequestProperty("Accept", "*/*");
		con.setRequestProperty("Accept-Encoding", "gzip;q=1.0,identity;q=0.8");
		con.setRequestProperty("Cache-Control", "no-cache");
	}
	
	public InputStream getHttpGetInputStream(String url){
		try{
			this.close();
			this.con = (HttpConnection)Connector.open(url,Connector.READ_WRITE,true);
			setConnection(this.con);
			con.setRequestMethod(HttpConnection.GET);
			int rc = con.getResponseCode();
			if(rc != HttpConnection.HTTP_OK){
				throw new IOException("Error Responsecode: " + rc);
			}
			return con.openInputStream();
		}
		catch(IOException e){
			ExceptionHandle.handle(e);
		}
		return null;
	}
	
	public InputStream getHttpPostInputStream(String url, byte[] data){
		try{
			this.close();
			this.con = (HttpConnection)Connector.open(url,Connector.READ_WRITE,true);
			setConnection(this.con);
			con.setRequestMethod(HttpConnection.POST);
			if(data != null)
				con.openOutputStream().write(data);
			
			int rc = con.getResponseCode();
			if(rc != HttpConnection.HTTP_OK){
				throw new IOException("Error Responsecode: " + rc);
			}
			return con.openInputStream();
		}
		catch(IOException e){
			ExceptionHandle.handle(e);
		}
		return null;
	}
	
	public void close() {
		if(this.con != null){
			try {
				this.con.close();
			} catch (IOException e) {
				ExceptionHandle.handle(e);
			}
		}
		this.con = null;
	}
}
